package com.general.seckill.common;

import lombok.Data;

import java.io.Serializable;

/**
 * @description: Result
 * @author: general
 * @version: 1.0
 * @create: 2022-04-30 22:52
 **/
@Data
public class Result<T> implements Serializable {


    protected boolean success = false;

    protected Integer code = 200;

    protected String msg = "";

    private T data;


    public Result(boolean success) {
        this.success = success;
        if (!success) {
            this.code = 500;
            this.msg = "失败";
        }
    }

    public Result() {
    }

    protected Result(boolean success, Integer code, String msg) {
        this.success = success;
        this.code = code;
        this.msg = msg;
    }

    protected Result(boolean success, T data, Integer code, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.success = success;
    }

    public static <T> Result<T> buildErrorResult(String message) {
        return new Result<>(false, null, message);
    }


    public static <T> Result<T> buildErrorResult(Integer code, String message) {
        return new Result<>(false, code, message);
    }

    public static <T> Result<T> buildErrorResult(Integer code, String message, T data) {
        return new Result<>(false, data, code, message);
    }


    public static <T> Result<T> buildSuccessResult(T data) {
        return new Result<>(true, data, 200, "成功");
    }

    public static <T> Result<T> buildSuccessResult() {
        return new Result<>(true);
    }


    /**
     * 泛型类型T建议重写toString方法
     *
     * @return String
     */
    @Override
    public String toString() {
        return "{\"success\":\"" + success + "\",\"code\":\"" + code + "\",\"message\":\"" + msg + "\",\"data\":\"" + data + "\"}";
    }

}

